import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { withRouter } from 'react-router';
import Table from '@knownsec/react-component/dist/Table';
import Pagination from '@knownsec/react-component/dist/Pagination';
import PageTable, { searchStringBuilder } from '@kuiper-components/page-table';
import EmptyData from '../../../components/empty/EmptyData';
import { gql, useQuery } from '@apollo/client';
import pathOr from 'ramda/es/pathOr';
import Detail from './Detail';
import { getParams, searchStringParams } from '../../../helpers/getUrlParams';
import { datetime } from '../../../../common/formatter';
import Breadcrumb, { Item } from '../../../components/Breadcrumb';
import Nonsupport from '../../../components/Nonsupport';
import Tooltip from '@knownsec/react-component/dist/Tooltip';
import s from './style.module.css';
import Toolbox from './Toolbox';
const planTimeOut = () => {
	const time = sessionStorage.getItem('planTimeOut');
	const now = time && Date.parse(datetime(time, 'YYYY-MM-DD'));
	if (!time || Date.now() > now) {
		return true;
	}
	return false;
};
const routePrefix = '/general/bug-store';

const columns = [
	{
		title: '漏洞名称',
		key: 'vuln_name',
		dataIndex: 'vuln_name',
		render(e) {
			return <Tooltip overlay={<div className={cn('')}>{e}</div>} placement={'top'}>
				<span className={cn('ell')}>{e}</span>
			</Tooltip>
		},
	},
	{
		title: '漏洞类型',
		key: 'vuln_type',
		dataIndex: 'vuln_type',
		render(actionMessage) {
			return actionMessage || '- - -';
		},
	},
	{
		title: '风险等级',
		key: 'level',
		dataIndex: 'level',
		render(affects) {
			return affects || '- - -';
		},
	},
	{
		title: '更新时间',
		key: 'updated_at',
		dataIndex: 'updated_at',
		render: e => {
			return datetime(e) || '- -';
		},
	},
	{
		title: '发布时间',
		key: 'created_at',
		dataIndex: 'created_at',
		render: e => {
			return datetime(e) || '- -';
		},
	},
	{
		title: '操作',
		key: 'description',
		dataIndex: 'description',
		render(description, item) {
			return <Detail detail={(description, item)} />;
		},
	},
];
function queryGQLBuilder() {
	return gql`
		query bug(
			$vuln_name: String = ""
			$vuln_type: String = ""
			$vuln_period: String = ""
			$page: Int = 1
			$limit: Int = 10
		) {
			dataPgination(
				vuln_type: $vuln_type
				vuln_period: $vuln_period
				vuln_name: $vuln_name
				page: $page
				limit: $limit
			) @rest(type: "bug", path: "/vulndb/get?{args}", endpoint: "v2") {
				code
				msg
				results {
					count
					data
				}
			}
		}
	`;
}
// const queryVariablesBuilder = ({ filter, page, perPage }) => {
// 	return {
// 		...filter,
// 		page,
// 		limit: perPage,
// 	};
// };
// const getTotal = pathOr(1, ['dataPgination', 'results', 'count']);

function OperationLog({ className, history, location }) {
	const params = getParams();
	const [filter, setFilter] = React.useState(
		params || {
			vuln_name: '',
			vuln_type: '',
			vuln_period: '',
			page: 1,
			limit: 10,
		}
	);
	// const filter = JSON.parse(
	// 	new URLSearchParams(location.search).get('filter') || '{}'
	// );
	const isoTime = d => {
		// d.setHours(d.getHours(), d.getMinutes() - d.getTimezoneOffset());
		return d.toISOString();
	};
	const [type, setType] = React.useState('empty');
	const { data, loading, refetch } = useQuery(queryGQLBuilder(), {
		variables: params || filter,
	});
	const { tableData, count } = React.useMemo(() => {
		if (data?.dataPgination) {
			const count = data?.dataPgination?.results?.count || 0;
			const dt = data?.dataPgination?.results?.data || [];
			return { count, tableData: dt };
		} else {
			return { count: 0, tableData: [] };
		}
	}, [data, filter]);
	const pageChange = (page, pageSize) => {
		const search = searchStringParams({
			...filter,
			page: page,
			limit: pageSize,
		});
		const obj = Object.assign({}, filter);
		obj.page = page;
		obj.limit = pageSize;
		setFilter(obj);
		refetch({ ...obj });
		history.replace(`${routePrefix}?${search}`);
	};
	const handleFilterChange = val => {
		const vulnperiod = val.vuln_period.startTime
			? `${isoTime(new Date(val.vuln_period.startTime))}_${isoTime(
					new Date(val.vuln_period.endTime)
			  )}`
			: null;
		val.vuln_period = vulnperiod;
		const search = searchStringBuilder(location.search, {
			...val,
			page: 1,
			sort: '_ID_DESC',
		});
		setFilter({ ...filter, ...val, page: 1, limit: 10 });
		refetch({ ...filter, ...val, page: 1, limit: 10 });
		history.replace(`${routePrefix}?${search}`);
	};
	React.useEffect(() => {
		if (!loading) setType('img');
	}, [loading]);
	return (
		<div className={cn(className, s.operationLog)}>
			<Breadcrumb>
				<Item key="operation-log" active>
					漏洞库
				</Item>
			</Breadcrumb>
			{planTimeOut() ? (
				<div className={s.content}>
					<Toolbox reSearch={() => {}} value={filter} />
					<div className={s.tableContainer}>
						<Table
							className={s.newnodata}
							columns={columns}
							data={[]}
							empty={<Nonsupport className={s.fff} />}
							pro
						/>
					</div>
				</div>
			) : (
				<div className={s.content}>
					<Toolbox reSearch={handleFilterChange} value={filter} />
					<div className={s.tableContainer}>
						<Table
							columns={columns}
							data={tableData}
							pro
							loading={loading}
							empty={<EmptyData type={type} className={s.nobor} />}
						/>
						{count > 10 && (
							<div className={s.df}>
								<Pagination
									current={filter.page || 1}
									pageSize={filter.limit || 10}
									pageSizeOptions={[10, 20, 50]}
									showSizeChanger
									showQuickJumper
									showTotal={total => `共${total}条`}
									total={count}
									onChange={pageChange}
								/>
							</div>
						)}
						{/* <PageTable
							columns={columns}
							routePrefix={routePrefix}
							queryGQLBuilder={queryGQLBuilder}
							queryVariablesBuilder={queryVariablesBuilder}
							getTotal={getTotal}
							getTableRows={getTableRows}
							getTablePageInfo={getTablePageInfo}
							gqlQueryOptions={{ nextFetchPolicy: 'cache-and-network' }}
						/> */}
					</div>
				</div>
			)}
		</div>
	);
}

OperationLog.propTypes = {
	className: PropTypes.string,
	history: PropTypes.objectOf(
		PropTypes.shape({
			push: PropTypes.func.isRequired,
		})
	),
	location: PropTypes.objectOf(
		PropTypes.shape({
			search: PropTypes.object,
		})
	),
};
OperationLog.defaultProps = {
	className: '',
};

export default withRouter(OperationLog);
